package main

import (
	"encoding/hex"
	"fmt"
	"time"
)

func hexToDateTime(yearHex, monthHex, dayHex, hourHex, minuteHex, secondHex string) (time.Time, error) {
	// 解析十六进制字符串
	yearBytes, err := hex.DecodeString(yearHex)
	if err != nil {
		return time.Time{}, err
	}
	year := int(yearBytes[0])<<8 + int(yearBytes[1])

	month, err := hex.DecodeString(monthHex)
	if err != nil {
		return time.Time{}, err
	}

	day, err := hex.DecodeString(dayHex)
	if err != nil {
		return time.Time{}, err
	}

	hour, err := hex.DecodeString(hourHex)
	if err != nil {
		return time.Time{}, err
	}

	minute, err := hex.DecodeString(minuteHex)
	if err != nil {
		return time.Time{}, err
	}

	second, err := hex.DecodeString(secondHex)
	if err != nil {
		return time.Time{}, err
	}

	// 构造 time.Time 对象
	dateTime := time.Date(year, time.Month(month[0]), int(day[0]), int(hour[0]), int(minute[0]), int(second[0]), 0, time.UTC)
	return dateTime, nil
}

func main() {
	// 假设十六进制表示如下
	yearHex := "07E4"    // 2020年
	monthHex := "06"     // 6月
	dayHex := "1A"       // 26日
	hourHex := "0F"      // 15时
	minuteHex := "3C"    // 60分，注意这里60实际上是不合法的，因为分和秒的范围是0-59，此处仅作为示例
	secondHex := "3C"    // 60秒，同上

	dateTime, err := hexToDateTime(yearHex, monthHex, dayHex, hourHex, minuteHex, secondHex)
	if err != nil {
		fmt.Println("Error converting hex to datetime:", err)
		return
	}

	fmt.Println("DateTime:", dateTime.Format("2006-01-02 15:04:05"))

	// 时间戳转回 hex
	time2hex()
}



func dateTimeToHex(dateTime time.Time) (yearHex, monthHex, dayHex, hourHex, minuteHex, secondHex string) {
	year := dateTime.Year()
	month := int(dateTime.Month())
	day := dateTime.Day()
	hour := dateTime.Hour()
	minute := dateTime.Minute()
	second := dateTime.Second()

	yearHex = fmt.Sprintf("%04X", year)
	monthHex = fmt.Sprintf("%02X", month)
	dayHex = fmt.Sprintf("%02X", day)
	hourHex = fmt.Sprintf("%02X", hour)
	minuteHex = fmt.Sprintf("%02X", minute)
	secondHex = fmt.Sprintf("%02X", second)

	return
}

func time2hex() {
	// 使用当前时间作为示例
	currentTime := time.Now().Local()

	yearHex, monthHex, dayHex, hourHex, minuteHex, secondHex := dateTimeToHex(currentTime)

	fmt.Println("Year Hex:", yearHex)
	fmt.Println("Month Hex:", monthHex)
	fmt.Println("Day Hex:", dayHex)
	fmt.Println("Hour Hex:", hourHex)
	fmt.Println("Minute Hex:", minuteHex)
	fmt.Println("Second Hex:", secondHex)
}
